import Vue from 'vue'
import Vuex from 'vuex'
import { register } from '@/api/user'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
    isAuthenticated: !!localStorage.getItem('token')
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      state.isAuthenticated = !!token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    LOGOUT(state) {
      state.token = ''
      state.userInfo = {}
      state.isAuthenticated = false
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    // // 登录
    // async login({ commit }, userInfo) {
    //   try {
    //     const response = await login(userInfo)
    //     if (response.code === 200) {
    //       commit('SET_TOKEN', response.data.token)
    //       commit('SET_USER_INFO', response.data.userInfo)
    //       return Promise.resolve(response)
    //     } else {
    //       return Promise.reject(response.message || '登录失败')
    //     }
    //   } catch (error) {
    //     return Promise.reject(error)
    //   }
    // },
    // 登录
    async login({ commit }) {
      commit('SET_TOKEN', "123456")
      commit('SET_USER_INFO', "admin")
    },
    // 注册
    async register({ commit }, userInfo) {
      try {
        const response = await register(userInfo)
        if (response.code === 200) {
          commit('SET_TOKEN', response.data.token)
          commit('SET_USER_INFO', response.data.userInfo)
          return Promise.resolve(response)
        } else {
          return Promise.reject(response.message || '注册失败')
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 登出
    logout({ commit }) {
      commit('LOGOUT')
      return Promise.resolve()
    }
  },
  getters: {
    isAuthenticated: state => state.isAuthenticated,
    userInfo: state => state.userInfo,
    token: state => state.token
  }
})
